package com.mucd.blog.common;

import com.mucd.blog.result.R;
import com.mucd.blog.statuscode.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author mucd
 */ /*
全局异常处理
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 异常处理方法
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //判断异常信息中是否含有Duplicate entry
        if (ex.getMessage().contains("Duplicate entry")) {
            //异常信息：Duplicate entry 'admin' for key 'idx_username'
            //用空格将异常信息分割
            String[] s = ex.getMessage().split(" ");
            //String msg = s[2] + "已被注册请更换用户名";
            String msg =  "此用户名太受欢迎,请更换一个";
            //String msg = s[2].replace("'","") + "已被注册请换个用户名";

            return R.error(msg);
        }
        log.error(ex.getMessage());
        return R.error("未知错误");
    }

    /**
     * 异常处理方法
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MyException.class)
    public R exceptionHandler(MyException ex) {
        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }

}
